import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:iidx_progress_tool/data/model/difficulty_progress.dart';
import 'package:iidx_progress_tool/data/model/tag.dart';
import 'package:iidx_progress_tool/data/services/tag_service.dart';

class TagEditDialog extends StatefulWidget {
  final DifficultyProgress progress;
  final Function onSave;

  const TagEditDialog({
    super.key,
    required this.progress,
    required this.onSave
  });

  @override
  State<StatefulWidget> createState() {
    return _TagEditDialogState();
  }
}

class _TagEditDialogState extends State<TagEditDialog> {
  TagService _tagService = TagService();
  List<Tag> _totalTags = [];
  Set<Tag> _selectedTags = {};

  @override
  void initState() {
    super.initState();
    widget.progress.tags.forEach((element) { _selectedTags.add(element);});
    _getTagList();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Select tags'),
      content: Wrap(
        direction: Axis.vertical,
        children: _buildTagList(),
      ),
      actions: [
        TextButton(
          child: const Text('取消'),
          onPressed: () {
            Navigator.of(context).pop();
          }
        ),
        TextButton(
          child: const Text('保存'),
          onPressed: () {
            _updateTags();
            Navigator.of(context).pop();
          }
        )
      ],
    );
  }

  void _getTagList() {
    Future<List<Tag>> tagList = _tagService.getTagList();
    tagList.then((_) {
      setState(() {
        _totalTags = _;
      });
    });
  }

  List<Widget> _buildTagList() {
    if (_totalTags.isEmpty) {
      return [];
    }

    return _totalTags.map((tag) {
      return ChoiceChip(
        label: Text(tag.name),
        selected: _selectedTags.contains(tag),
        onSelected: (selected) {
          setState(() {
            if (selected) {
              _selectedTags.add(tag);
            } else {
              _selectedTags.remove(tag);
            }
          });
        }
      );
    }).toList();
  }

  void _updateTags() {
    setState(() {
      widget.progress.tags = _selectedTags.toList();
      widget.onSave();
    });
  }
}